#include "GameOverLayer.h"
#include "PlayScene.h"
#include "MenuScene.h"
#include "GlobalDefine.h"
#include "SimpleAudioEngine.h"
USING_NS_CC;

GameOverLayer* GameOverLayer::create(const ccColor4B& color)
{
	if(g_isSound) 
	{
		CocosDenshion::SimpleAudioEngine *audioEngine = CocosDenshion::SimpleAudioEngine::sharedEngine();
		audioEngine->pauseBackgroundMusic();
		audioEngine->playEffect("lose.wav", false);
	}

    GameOverLayer *pRet = new GameOverLayer();
    pRet->initWithColor(color);
    pRet->autorelease();
    return pRet;
}

bool GameOverLayer::initWithColor(const ccColor4B& color)
{
    if (!CCLayerColor::initWithColor(color)) {
        return false;
    }

    CCSize winSize = CCDirector::sharedDirector()->getWinSize();
    CCPoint centerPos = CCPoint(winSize.width / 2, winSize.height / 2);
    CCPoint origin = CCDirector::sharedDirector()->getVisibleOrigin();

	CCSprite* pSprite = CCSprite::create("game_over.png");
    
    // position the sprite on the center of the screen
    pSprite->setPosition(ccp(winSize.width/2 + origin.x, winSize.height - 160/2 - 5));
    
    // add the sprite as a child to this layer
    this->addChild(pSprite, 0);

    CCMenuItemSprite *itemRestart = CCMenuItemSprite::create(CCSprite::create("bt_restart.png"),
		CCSprite::create("bt_restart_select.png"),
		this, menu_selector(GameOverLayer::onRestart));
	CCMenu *menuRestart = CCMenu::create();
	menuRestart->addChild(itemRestart, 1);
	menuRestart->setPosition(centerPos.x, 155);

	CCMenuItemSprite *itemMenu = CCMenuItemSprite::create(CCSprite::create("bt_menu.png"),
		CCSprite::create("bt_menu_select.png"),
		this, menu_selector(GameOverLayer::onBackMenu));
	CCMenu *menuBackMenu = CCMenu::create();
	menuBackMenu->addChild(itemMenu, 1);
	menuBackMenu->setPosition(centerPos.x, 65);

    this->addChild(menuRestart, 1);
	this->addChild(menuBackMenu, 2);

	CCSize visibleSize = CCDirector::sharedDirector()->getVisibleSize();

	this->labelCoin = CCLabelTTF::create("Your Coins: 0", "Arial", 35);
	this->labelCoin->setPosition(ccp(visibleSize.width/2, visibleSize.height - 240));
	this->labelCoin->setString(CCString::createWithFormat("Your Coins: %ld", g_coins)->getCString());
    this->addChild(this->labelCoin);
    
    this->labelMeter = CCLabelTTF::create("Your Meter: 0", "Arial", 35);
    this->labelMeter->setPosition(ccp(visibleSize.width/2, visibleSize.height - 180));
	this->labelMeter->setString(CCString::createWithFormat("Your Meter: %ld", g_scores)->getCString());
    this->addChild(this->labelMeter);
    
    return true;
}

void GameOverLayer::onRestart(CCObject* pSender)
{
	g_isGameOver = false;
	CCDirector::sharedDirector()->resume();
    CCDirector::sharedDirector()->replaceScene(PlayLayer::scene());
}

void GameOverLayer::onBackMenu(CCObject* pSender)
{
    CCDirector::sharedDirector()->replaceScene(MenuScene::scene());
	g_isGameOver = false;
    CCDirector::sharedDirector()->resume();
}